package com.ztercelstudio.demo004

import android.util.Log
import java.lang.Thread.currentThread
import java.util.concurrent.Executors

class TestThread: Thread() {
    override fun run() {
        for (i in 1..10) {
            Log.d("Demo004", "TestThread => thread(${currentThread().id}) - ${i}")
        }
    }
}

class TestRunnable: Runnable {
    override fun run() {
        for (i in 1..10) {
            Log.d("Demo004", "TestRunnable => thread(${currentThread().id}) - ${i}")
        }
    }
}

class TestSync {

    var count: Int = 0

    @Synchronized
    fun time() {
        count++
        Log.d("Demo004", "TestSync => thread(${currentThread().id}) - ${count}")
    }
}

fun sampleEntry() {

    Log.d("Demo004", "Thread debug ... ")

    // Thread 子类创建线程
    val thread1 = TestThread()
    thread1.start()
    thread1.join()

    // Runnable 创建线程
    val thread2 = Thread(TestRunnable())
    thread2.start()
    thread2.join()

    // Thread 创建匿名线程
    val thread3 = Thread {
        for (i in 1..10) {
            Log.d("Demo004", "Thread => thread(${currentThread().id}) - ${i}")
            Thread.sleep(1000)
        }
    }
    thread3.start()
    thread3.join()

    // 线程池
    val executor1 = Executors.newFixedThreadPool(10)
    executor1.submit{
        for (i in 1..10) {
            Log.d("Demo004", "Executors submit1 => thread(${currentThread().id}) - ${i}")
        }
    }
    executor1.submit{
        for (i in 1..10) {
            Log.d("Demo004", "Executors submit2 => thread(${currentThread().id}) - ${i}")
        }
    }

    executor1.execute{
        for (i in 1..10) {
            Log.d("Demo004", "Executors execute => thread(${currentThread().id}) - ${i}")
        }
    }
    executor1.shutdown()
    
    val executor2 = Executors.newFixedThreadPool(5)
    val testSync = TestSync();
    for (i in 1..10) {
        executor2.execute{
            testSync.time()
        }
    }
    executor2.shutdown()
}